const express = require('express');
const SeedService = require('../services/seedService');
const User = require('../models/User');
const { auth, requireAdmin } = require('../middleware/auth');

const router = express.Router();

// 所有管理员路由都需要认证和管理员权限
router.use(auth);
router.use(requireAdmin);

/**
 * @route   POST /api/admin/seed
 * @desc    初始化种子数据
 * @access  Admin
 */
router.post('/seed', async (req, res) => {
  try {
    const result = await SeedService.initializeAll();
    
    res.json({
      success: true,
      message: '种子数据初始化完成',
      data: result
    });

  } catch (error) {
    console.error('种子数据初始化错误:', error);
    res.status(500).json({
      success: false,
      message: '种子数据初始化失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

/**
 * @route   GET /api/admin/stats
 * @desc    获取数据库统计信息
 * @access  Admin
 */
router.get('/stats', async (req, res) => {
  try {
    const stats = await SeedService.getDatabaseStats();
    
    res.json({
      success: true,
      data: { stats }
    });

  } catch (error) {
    console.error('获取统计信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取统计信息失败'
    });
  }
});

/**
 * @route   POST /api/admin/validate
 * @desc    验证数据完整性
 * @access  Admin
 */
router.post('/validate', async (req, res) => {
  try {
    const validation = await SeedService.validateData();
    
    res.json({
      success: true,
      message: '数据验证完成',
      data: validation
    });

  } catch (error) {
    console.error('数据验证错误:', error);
    res.status(500).json({
      success: false,
      message: '数据验证失败'
    });
  }
});

/**
 * @route   GET /api/admin/users
 * @desc    获取所有用户（包括管理信息）
 * @access  Admin
 */
router.get('/users', async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const skip = (page - 1) * limit;

    const users = await User.find({})
      .select('username email name avatar bio location isActive isVerified isAdmin followersCount followingCount lastLoginAt createdAt updatedAt')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    const total = await User.countDocuments({});

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败'
    });
  }
});

/**
 * @route   PUT /api/admin/users/:id/status
 * @desc    更新用户状态（激活/禁用）
 * @access  Admin
 */
router.put('/users/:id/status', async (req, res) => {
  try {
    const { isActive } = req.body;
    const userId = req.params.id;

    // 防止管理员禁用自己
    if (req.user.userId.toString() === userId) {
      return res.status(400).json({
        success: false,
        message: '不能修改自己的状态'
      });
    }

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    user.isActive = isActive;
    await user.save();

    res.json({
      success: true,
      message: `用户已${isActive ? '激活' : '禁用'}`,
      data: {
        user: {
          id: user._id,
          username: user.username,
          name: user.name,
          isActive: user.isActive
        }
      }
    });

  } catch (error) {
    console.error('更新用户状态错误:', error);
    res.status(500).json({
      success: false,
      message: '更新用户状态失败'
    });
  }
});

/**
 * @route   PUT /api/admin/users/:id/verify
 * @desc    设置用户验证状态
 * @access  Admin
 */
router.put('/users/:id/verify', async (req, res) => {
  try {
    const { isVerified } = req.body;
    const userId = req.params.id;

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    user.isVerified = isVerified;
    await user.save();

    res.json({
      success: true,
      message: `用户验证状态已${isVerified ? '开启' : '关闭'}`,
      data: {
        user: {
          id: user._id,
          username: user.username,
          name: user.name,
          isVerified: user.isVerified
        }
      }
    });

  } catch (error) {
    console.error('更新用户验证状态错误:', error);
    res.status(500).json({
      success: false,
      message: '更新用户验证状态失败'
    });
  }
});

/**
 * @route   DELETE /api/admin/clear-data
 * @desc    清空所有数据 (危险操作)
 * @access  Admin
 */
router.delete('/clear-data', async (req, res) => {
  try {
    const { confirm } = req.body;
    
    if (confirm !== 'CLEAR_ALL_DATA') {
      return res.status(400).json({
        success: false,
        message: '需要确认操作，请发送 { "confirm": "CLEAR_ALL_DATA" }'
      });
    }

    await SeedService.clearAllData();
    
    res.json({
      success: true,
      message: '所有数据已清空'
    });

  } catch (error) {
    console.error('清空数据错误:', error);
    res.status(500).json({
      success: false,
      message: '清空数据失败'
    });
  }
});

module.exports = router; 